import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Select } from 'antd';
import Upload from '../../components/Upload/Upload'
import axios from '../../aixos'
import { connect } from 'react-redux'
import WangEditor from '../../components/WangEditor/WangEditor'


const { TextArea } = Input
const { Option } = Select

function Add(props) {
  console.log(props)
  const [categoryList, setCategoryList] = useState([])
  const [cover, setCover] = useState('')
  const [form] = Form.useForm();
  const [content, setContent] = useState('') // 编辑器内容

  useEffect(() => {
    // 获取分类
    axios.get('/category').then(res => {
      setCategoryList(res.data)
    })
  }, [])

  console.log(props)
  const { id } = props.match.params
  useEffect(() => {
    if (id) {
      axios.get(`/article/${id}`).then(res => {
        const { category, title, description, cover, content } = res.data
        form.setFieldsValue({
          category: category._id,
          title,
          description,
        })
        setCover(cover)
        setContent(content)
      })
    }
  }, [id, form])


  const handleChange = () => {}
  const submit = () => {
    form.validateFields().then(res => {
      console.log(res)
      if (!id) {
        axios.post('/article', {
          author: props.userId,
          ...res,
          cover,
          content
        }).then(() => {
          props.history.replace('/article/list')
        })
      } else {
        axios.put('/article', {
          id,
          author: props.userId,
          ...res,
          cover,
          content
        }).then(() => {
          props.history.replace('/article/list')
        })
      }
    })
  }
  
  return (
    <div>
      <Form
      form={form}
      layout="vertical"
    >
      <Form.Item label="分类" name="category" required rules={
        [
          {
            required: true,
            message: '请选择分类'
          }
        ]
      }>
      <Select onChange={handleChange} placeholder='请选择分类'>
        {
          categoryList.map(item => <Option value={item._id} key={item._id}>{item.name}</Option>)
        }
        
      </Select>
      </Form.Item>
      <Form.Item label="标题" name="title" required rules={
        [
          {
            required: true,
            message: '请输入标题'
          }
        ]
      }>
        <Input placeholder="请输入标题" />
      </Form.Item>
      <Form.Item label="简介" name="description" required rules={
        [
          {
            required: true,
            message: '请输入简要描述'
          }
        ]
      }>
        <TextArea rows={4} placeholder="请输入简要描述"/>
      </Form.Item>
      <Form.Item label="封面图片" name="cover">
        <Upload imageUrl={cover} setImageUrl={(url) => setCover(url)} />
      </Form.Item>
      <Form.Item label="内容" name="content" required rules={
        [
          {
            validator: () => {
              console.log('content', content)
              console.log('content', content === '<p><br></p>')
              if (content === '<p><br></p>') {
                return Promise.reject(new Error('请编写内容'))
              } else {
                return Promise.resolve()
              }
            }
          },
        ]
      }>
        <WangEditor content={content} getHtml={setContent} />
      </Form.Item>
      <Form.Item>
        <Button type="primary" onClick={submit}>提交</Button>
      </Form.Item>
    </Form>
    </div>
  )
}

export default connect((state) => {
  return {
    userId: state.userReducer._id
  }
})(Add)
